package user

import (
	"gq_volunteer_platform/bean"
	"gq_volunteer_platform/model/admin"
	"gq_volunteer_platform/model/organization"
	"gq_volunteer_platform/model/user"
	"time"

	"github.com/gin-gonic/gin"
)

func Info(c *gin.Context) {
	// 获取登录用户对象
	var u user.User
	if err := u.Get(c); err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	// 更新数据
	var two user.User
	two.ID = u.ID
	two.LastIp = c.ClientIP()
	two.LastLoginTime = time.Now().Format(time.DateTime)

	//
	if err := bean.MysqlDb.Updates(&two).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	// 返回数据
	var info user.User

	if err := bean.MysqlDb.Where("`id`=?", u.ID).First(&info).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	c.PureJSON(200, info)
}

func Edit(c *gin.Context) {
	// 获取登录用户对象
	var u user.User
	if err := u.Get(c); err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	var req struct {
		Name         string `binding:"max=255"`
		ProfilePhoto string `binding:"max=255"`

		RealName     string `binding:"max=255"`
		IdcardType   string `binding:"oneof='' 身份证 军官证 学生证 其他证件"`
		Idcard       string `binding:"max=255"`
		MobileNumber string `binding:"max=255"`
		Sex          string `binding:"oneof='' 男 女"`
		Email        string `binding:"max=255"`
		Ethnicity    string `binding:"max=255"`

		PoliticalStatus       string `binding:"oneof='' 中共党员 共青团员 群众 其他"`
		EducationLevel        string `binding:"oneof='' 小学 初中 高中 大学 研究生 博士 其他"`
		EmploymentStatus      string `binding:"oneof='' 公务员 教师 学生 军人 工人 农民 医务人员 科技人员 企事业单位 下岗职工 其他"`
		LivingAddress         string `binding:"max=255"`
		AffiliatedUnitAddress string `binding:"max=255"`
		AllowNotice           string `binding:"oneof='' true false"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	// 其他属性不更新
	var three user.User
	three.ID = u.ID
	three.Name = req.Name
	three.ProfilePhoto = req.ProfilePhoto

	three.RealName = req.RealName
	three.IdcardType = req.IdcardType
	three.Idcard = req.Idcard
	three.MobileNumber = req.MobileNumber
	three.Sex = req.Sex
	three.Email = req.Email
	three.Ethnicity = req.Ethnicity
	// three.Qq = req.Qq
	// three.Weibo = req.Weibo

	// three.HealthStatus = req.HealthStatus
	three.PoliticalStatus = req.PoliticalStatus
	three.EducationLevel = req.EducationLevel
	// three.ForeignLanguage = req.ForeignLanguage
	three.EmploymentStatus = req.EmploymentStatus
	three.LivingAddress = req.LivingAddress
	// three.DetailedAddress = req.DetailedAddress
	// three.AffiliatedUnit = req.AffiliatedUnit
	three.AffiliatedUnitAddress = req.AffiliatedUnitAddress

	three.AllowNotice = req.AllowNotice

	// three.ServicePreference = req.ServicePreference
	// three.ServiceTarget = req.ServiceTarget
	// three.ServiceTime = req.ServiceTime
	// three.ServiceArea = req.ServiceArea
	// three.ServiceDomain = req.ServiceDomain

	// 不更新空值
	if err := bean.MysqlDb.Updates(&three).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	c.String(200, "ok")
}

// 修改个人信息 并且 申请加入
func EditAndApply(c *gin.Context) {
	// 获取登录用户对象
	var u user.User
	if err := u.Get(c); err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	var req struct {
		OrganizationId uint   `binding:"required,gte=1,max=10000000"`
		Name           string `binding:"max=255"`
		ProfilePhoto   string `binding:"max=255"`

		RealName     string `binding:"max=255"`
		IdcardType   string `binding:"oneof='' 身份证 军官证 学生证 其他证件"`
		Idcard       string `binding:"max=255"`
		MobileNumber string `binding:"max=255"`
		Sex          string `binding:"oneof='' 男 女"`
		Email        string `binding:"max=255"`
		Ethnicity    string `binding:"max=255"`

		PoliticalStatus       string `binding:"oneof='' 中共党员 共青团员 群众 其他"`
		EducationLevel        string `binding:"oneof='' 小学 初中 高中 大学 研究生 博士 其他"`
		EmploymentStatus      string `binding:"oneof='' 公务员 教师 学生 军人 工人 农民 医务人员 科技人员 企事业单位 下岗职工 其他"`
		LivingAddress         string `binding:"max=255"`
		AffiliatedUnitAddress string `binding:"max=255"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}
	// 待申请状态可调用
	if u.CheckStatus == "已审核" {
		bean.Log.Warning("您已经通过审核")
		c.String(400, "您已经通过审核")
		return
	}

	// 其他属性不更新
	var three user.User
	three.OrganizationId = req.OrganizationId
	three.ID = u.ID
	three.Name = req.Name
	three.ProfilePhoto = req.ProfilePhoto

	three.RealName = req.RealName
	three.IdcardType = req.IdcardType
	three.Idcard = req.Idcard
	three.MobileNumber = req.MobileNumber
	three.Sex = req.Sex
	three.Email = req.Email
	three.Ethnicity = req.Ethnicity
	// three.Qq = req.Qq
	// three.Weibo = req.Weibo

	// three.HealthStatus = req.HealthStatus
	three.PoliticalStatus = req.PoliticalStatus
	three.EducationLevel = req.EducationLevel
	// three.ForeignLanguage = req.ForeignLanguage
	three.EmploymentStatus = req.EmploymentStatus
	three.LivingAddress = req.LivingAddress
	// three.DetailedAddress = req.DetailedAddress
	// three.AffiliatedUnit = req.AffiliatedUnit
	three.AffiliatedUnitAddress = req.AffiliatedUnitAddress

	// three.ServicePreference = req.ServicePreference
	// three.ServiceTarget = req.ServiceTarget
	// three.ServiceTime = req.ServiceTime
	// three.ServiceArea = req.ServiceArea
	// three.ServiceDomain = req.ServiceDomain
	// 待申请 待审核 已驳回 =》待审核状态
	if u.CheckStatus != "已审核" {
		three.CheckStatus = "待审核"
	}

	// 不更新空值
	if err := bean.MysqlDb.Updates(&three).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	c.String(200, "ok")
}

// 变更机构状态
func ChangeStatus(c *gin.Context) {
	// 获取登录用户对象
	var u user.User
	if err := u.Get(c); err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	var one struct {
		OrganizationId       uint
		ChangeOrganizationId uint
		ChangeStatus         string
		ChangeNote           string
	}

	one.ChangeOrganizationId = u.ChangeOrganizationId
	one.OrganizationId = u.OrganizationId
	one.ChangeStatus = u.ChangeStatus
	one.ChangeNote = u.ChangeNote

	c.PureJSON(200, one)
}

// 变更机构
func ChangeOrganization(c *gin.Context) {
	// 获取登录用户对象
	var u user.User
	if err := u.Get(c); err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	var req struct {
		ChangeOrganizationId uint   `binding:"max=10000000"`
		ChangeNote           string `binding:"max=255"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	var org organization.Organization
	if err := bean.MysqlDb.Where("`id`=?", req.ChangeOrganizationId).First(&org).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	var two user.User
	two.ID = u.ID
	two.ChangeOrganizationId = req.ChangeOrganizationId
	two.ChangeNote = req.ChangeNote
	two.ChangeStatus = "待审核"

	if err := bean.MysqlDb.Updates(&two).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, "数据库错误")
		return
	}

	c.String(200, "ok")
}

// 用户注销
func Exist(c *gin.Context) {
	// 获取登录用户对象
	var u user.User
	if err := u.Get(c); err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	// 申请过退出则，不能再次申请
	var one user.UserExist
	if err := bean.MysqlDb.Where("`user_id`=?", u.ID).Limit(1).Find(&one).Error; err != nil {
		bean.Log.Error(err)
		c.String(400, err.Error())
		return
	}

	if one.ID != 0 {
		if one.Status == "已驳回" {
			c.String(400, "您的申请已被驳回，请联系管理人员")
		} else {
			c.String(400, "您的申请已提交，请耐心等待")
		}
		return
	}

	var two user.UserExist
	two.Status = "待审核"
	two.UserId = u.ID

	if err := bean.MysqlDb.Create(&two).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, "数据库错误")
		return
	}

	c.String(200, "ok")
}

// 绑定管理员账号（微信小程序二维码）
func BindAdmin(c *gin.Context) {
	// 获取登录用户对象
	var u user.User
	if err := u.Get(c); err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	var req struct {
		AdminToken string `binding:"max=255"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	// 验证token是否正确
	var one admin.Admin

	if err := bean.MysqlDb.Where("`token`=?", req.AdminToken).First(&one).Error; err != nil {
		bean.Log.Error(err)
		c.String(400, err.Error())
		return
	}

	// 删除其他的绑定账号
	var old []admin.Admin
	if err := bean.MysqlDb.Where("`user_id`=?", u.ID).Find(&old).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	for _, v := range old {
		var oldTmp admin.Admin
		oldTmp.ID = v.ID
		oldTmp.UserId = 0 // 解绑
		if err := bean.MysqlDb.Select("user_id").Updates(&oldTmp).Error; err != nil {
			bean.Log.Error(err)
			c.String(500, err.Error())
			return
		}
	}

	// 其他属性不更新
	// 不更新空值
	var two admin.Admin
	two.ID = one.ID
	two.UserId = u.ID

	if err := bean.MysqlDb.Updates(&two).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	c.String(200, "ok")
}

// 二维码登录确认
func QrCodeLoginConfirm(c *gin.Context) {
	// 获取登录用户对象
	var u user.User
	if err := u.Get(c); err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	var req struct {
		Ticket    string `binding:"alphanum,len=32"`
		Confirmed string `binding:"oneof=允许 拒绝"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	// 查询user绑定的admin
	var adm admin.Admin
	if err := bean.MysqlDb.Where("`user_id`=?", u.ID).First(&adm).Error; err != nil {
		bean.Log.Error(err)
		c.String(400, "用户未绑定管理员账号,请登录后台绑定后操作")
		return
	}

	var one admin.AdminQrTicket
	if err := bean.MysqlDb.Where("`ticket`=?", req.Ticket).First(&one).Error; err != nil {
		bean.Log.Error(err)
		c.String(400, "二维码已失效")
		return
	}

	// 其他属性不更新
	var two admin.AdminQrTicket
	two.ID = one.ID
	two.AdminId = adm.ID
	two.Confirmed = req.Confirmed

	// 不更新空值
	if err := bean.MysqlDb.Updates(&two).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	c.String(200, "ok")
}
